//
//  YBWeightInputController.m
//  孕妙
//
//  Created by Raoy on 16/4/11.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "YBWeightInputController.h"
#import "YBSelectPickerWindow.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "YBBodyFatView.h"


typedef NS_ENUM(NSInteger, weightScale){
    lefuScale,
    vScale,
    eBelterScale
};


@interface YBWeightInputController ()<UIPickerViewDelegate, UIPickerViewDataSource, CBCentralManagerDelegate, CBPeripheralDelegate>
@property (strong, nonatomic) YBSelectPickerWindow *pickerWindow;

@property(nonatomic, strong)CBCentralManager *mgr;
@property(nonatomic, strong)NSMutableArray   *peripherals;
//当前外设
@property(nonatomic, strong)CBPeripheral  *peripheral;

//当前外设的服务和特征
@property(nonatomic, strong)CBCharacteristic    *dataInteractCharacteristic;
@property(nonatomic, strong)CBCharacteristic    *peripheralInfoCharacteristic;
@property(nonatomic, assign)weightScale scalePer;
@property (nonatomic, assign) BOOL isMeasureError;
@property (nonatomic, strong)YBBodyFatView *bodyfatView;
//@property (nonatomic, assign, getter = isLefuScale) BOOL lefuScale;
//@property (nonatomic, assign, getter= isBelter) BOOL eBelter;
@end

@implementation YBWeightInputController
{
    NSMutableArray *intArray; //选择器整数部分
    NSArray *floatArray;   //选择器小数部分
    NSString *selectIntStr;    //获取整数值
    NSString *selectFloatStr;  //获取小数值
    NSString *valueStr;
    
    NSInteger _ageInt; //年龄
    NSInteger _heightInt;//身高
    NSInteger _statusint;//运动强度
    float _jiRouScale;

//    int  _weightInt;
}

static dispatch_once_t onceAnalyseData;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"记录体成分";
    
    self.view.backgroundColor =  SYColor(245, 245, 245);;
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"YB_backToSupper"  highIcon:nil target:self action:@selector(clickLeftButtonToSupper2:)];
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    
    [self.rightBtn addTarget:self action:@selector(righeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self scanBle];
    //开始使用蓝牙设备测量
    [self.startbtn2 addTarget:self action:@selector(weightopenBle:) forControlEvents:UIControlEventTouchUpInside];
    //设置小数，整数范围
    intArray = [NSMutableArray array];
    floatArray = @[@"0", @"1", @"2", @"3", @"4",@"5", @"6", @"7",@"8", @"9"];
    for (int index = 30; index < 150; index++) {
        NSString *str = [NSString stringWithFormat:@"%d", index];
        [intArray addObject:str];
    }
    //设置日期栏
    [self setTitle:@"请输入体重:" buyTitle:@"购买体脂计" indexImage:1];
    //设置体重
    valueStr = @" kg";
    [self createLabel:valueStr];
    _bodyfatView = [[YBBodyFatView alloc] initWithFrame:CGRectMake(0, SYNavigateHeight + 70 * (DeviceWidth / 480), DeviceWidth, DeviceHeight)];
    _bodyfatView.hidden = YES;
    
    
//    [self.view addSubview:_bodyfatView];
    
    // Do any additional setup after loading the view.
}

#pragma mark - Private Methods
- (void)righeBtnClick:(id)sender
{
    self.fuGaiView.hidden = NO;
    if (_pickerWindow == nil) {
        _pickerWindow = [[YBSelectPickerWindow alloc] init];
        [_pickerWindow setInterFace:@"体重(kg)"];
         [_pickerWindow addSubview:_pickerWindow.dianL];
        _pickerWindow.selectPickerView.delegate = self;
        _pickerWindow.selectPickerView.dataSource = self;
    }else{
        
        _pickerWindow.hidden = NO;
    }
    [_pickerWindow.selectPickerView selectRow:27  inComponent:0 animated:YES];
    [_pickerWindow.selectPickerView selectRow:floatArray.count / 2  inComponent:1 animated:YES];
    selectIntStr = intArray[27];
    selectFloatStr = floatArray[floatArray.count / 2];
    [_pickerWindow.sureBtn addTarget:self action:@selector(saveWeightDataBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_pickerWindow.cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)saveWeightDataBtn:(UIButton *)btn
{
//    sleep(1);
    valueStr = nil;
    self.fuGaiView.hidden = YES;
    _pickerWindow.hidden = YES;
    valueStr = [NSString stringWithFormat:@"%@.%@ kg", selectIntStr, selectFloatStr];
    [self createLabel:valueStr];
    [self.view setNeedsDisplay];
    [self getUserParmaterData:[NSString stringWithFormat:@"%@.%@", selectIntStr, selectFloatStr] selectionValue:1 gaoxueya:nil];
}

- (void)cancelBtnClicked:(id)sender
{
    self.fuGaiView.hidden = YES;
}

- (void)clickLeftButtonToSupper2:(id)sender
{
    self.pickerWindow.selectPickerView = nil;
    self.pickerWindow = nil;  //释放内存
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    NSLog(@"sfeawrr------");
    [super viewDidAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
   
    self.pickerWindow = nil;
    [super viewWillDisappear:YES];
}

- (void)weightopenBle:(UIButton *)button
{
    onceAnalyseData = 0;
    [self scanBle];
}

//获取用户信息
- (void)getUserInformationData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [[NSURL alloc] initWithString:URL_Health_baby_getDevAccountInfo];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
        request.HTTPMethod = @"POST";
        NSString *str = [NSString stringWithFormat:@"account=%@&userName=*",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"]];
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
         NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [request setHTTPBody:data];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSArray *arr = [dict objectForKey:@"data"];
                NSDictionary *dic = [arr lastObject];
                //出生日期
                NSString *date = [dic objectForKey:@"age"];
                NSString *yeardate = [date substringToIndex:4];

             
                NSUInteger unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday;
                
                //现在时间
                NSCalendar *calendar2 = [NSCalendar currentCalendar];
                NSDateComponents *nowCmps = [calendar2 components:unit fromDate:[NSDate date]];
                //年龄
                _ageInt = (long)nowCmps.year - [yeardate integerValue];
                //身高
                _heightInt = [[dic objectForKey:@"height"] integerValue];
                //运动强度
                _statusint = [[dic objectForKey:@"status"] integerValue];          
                
            }else
            {
                [MBProgressHUD showError:@"获取用户信息失败"];
            }
        }];
    });
}


#pragma mark - UIPickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSLog(@"intArray.count = %ld", intArray.count);
    if (component == 0) {
        return intArray.count;
    } else {
        return floatArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return  intArray[row];
    } else {
        
        return  floatArray[row];
    }
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        selectIntStr = intArray[row];
    } else {
        selectFloatStr = floatArray[row];
    }
  
}

#pragma mark- 连接蓝牙外设


- (NSMutableArray *)peripherals
{
    if (!_peripherals)
    {
        _peripherals = [NSMutableArray array];
    }
    
    return _peripherals;
}

- (CBCentralManager *)mgr
{
    if (!_mgr){
        
        self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    return _mgr;
}

- (void)scanBle
{
    
    self.useAddviceWindow.hidden = YES;
    self.startbtn2.isAccessibilityElement = NO;
    [MBProgressHUD showMessage:@"正在搜索设备......"];
    [self.mgr stopScan];
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    self.startbtn2.isAccessibilityElement = YES;
}



#pragma mark -- CBCentralManagerDelegate
//检查设备是否支持蓝牙
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:// 蓝牙打开
            NSLog(@"CBCentralManagerStatePoweredOn");
            [self.mgr scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStatePoweredOff://蓝牙关闭
            NSLog(@"CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"State Unsupported");
            break;
            
        default:
            NSLog(@"Central Manager Did Update State");
            break;
    }
    
}


//发现外设
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"发现外设：%@  ", peripheral.name);
    [MBProgressHUD hideHUD];
    if (![self.peripherals containsObject:peripheral]) {
        if ([peripheral.name hasPrefix:@"Electronic Scale"]) {
            _scalePer = lefuScale;
            peripheral.delegate = self;
            [self.peripherals addObject:peripheral];
            
        } else if ([peripheral.name hasPrefix:@"VScale"]){
            _scalePer = vScale;
            peripheral.delegate = self;
            [self.peripherals addObject:peripheral];
        }else if ([peripheral.name hasPrefix:@"eBody-Fat-Scale"]){
            _scalePer = eBelterScale;
            peripheral.delegate = self;
            [self.peripherals addObject:peripheral];
        }else{
            return;
        }
    }
    
    
    NSLog(@"找到了 %@", peripheral.name);
    
    for (CBPeripheral *per in self.peripherals) {
        NSLog(@"外设：%@", per);
        if (per.state == NO) {
            self.peripheral = peripheral;
            [self.mgr connectPeripheral:self.peripheral options:nil];
        }
    }
    
    
}

//连接某个外设的时候调用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"连接外设成功");
    [self.mgr stopScan];
    [self getUserInformationData];
    // 查找外设中的所有服务
    //#warning 通过传入一个存放服务UDID的数组进去，过滤掉一些不要的服务
    [peripheral discoverServices:nil];
    
}




#pragma mark - CBPeriperalDelegate

//外设已经查找到的服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (self.useAddviceWindow.hidden == NO && self.useAddviceWindow != nil) {
        [self.mgr stopScan];
        self.peripheral = nil;
        self.mgr = nil;
        return;
    }
    NSLog(@"发现服务  %@", peripheral.services);
//    NSString *uuidStr = self.isLefuScale ? @"0xFFF0" : @"F433BD80-75B8-11E2-97D9-0002A5D5C51B";
    NSString *uuidStr = nil;
    if (_scalePer == vScale) {
        uuidStr = @"F433BD80-75B8-11E2-97D9-0002A5D5C51B";
    } else {
        uuidStr = @"0xFFF0";
    }
    // 遍历所有的服务
    for (CBService *service in peripheral.services) {
        // 过滤其他服务, 匹配自己想要的服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:uuidStr]]) {
            
            //#warning 通过传入一个存放特征UDID的数组进去，过滤掉一些不要的特征
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    
}

//连接断开时
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    self.peripheral = nil;
    onceAnalyseData = 0;
    [self.mgr scanForPeripheralsWithServices:nil options:nil];
    [self.peripherals removeAllObjects];
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙断开"]];
    NSLog(@"蓝牙连接已断开");
}

//特征值匹配
//static dispatch_once_t onceToken;

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"didDiscoverCharacteristicsForService: %@", service.characteristics);
    onceAnalyseData = 0;
    [self.buletoothImageView setImage:[UIImage imageNamed:@"蓝牙连接"]];
    [self.view setNeedsDisplay];
    
    [self.peripherals removeAllObjects];
    NSString *uuidWRStr = nil;
    NSString *uuidOWStr = nil;
    switch (_scalePer) {
        case lefuScale:
            uuidWRStr = @"0xFFF4";
            uuidOWStr = @"0XFFF1";
            break;
        case vScale:
            uuidWRStr = @"1a2ea400-75b9-11e2-be05-0002a5d5c51b";
            uuidOWStr =  @"29f11080-75b9-11e2-8bf6-0002a5d5c51b";
            break;
        case eBelterScale:
            uuidWRStr = @"0xFFF4";
            uuidOWStr = @"0xFFF3";
            break;
        default:
            break;
    }
    
//    NSString *uuidWRStr = self.isLefuScale ? @"0xFFF4" : @"1a2ea400-75b9-11e2-be05-0002a5d5c51b";
//    NSString *uuidOWStr = self.isLefuScale ? @"0xFFF1" : @"29f11080-75b9-11e2-8bf6-0002a5d5c51b";
    // 遍历所有的特征
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"--%@---", characteristic.UUID);
        
        //过滤不想要的特征
        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidWRStr]]){
            NSLog(@"--已找到特征0xFFF1, 注册监听  ");
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
        
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidOWStr]]) {
            NSLog(@"--已找到特征0xFFF2 ,发数据到外设 ");
            
            double delayTime = 0.5;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                //发送数据到蓝牙外设
                [self selectRequestDatatoBule:characteristic];
                double delayInSeconds1 = 0.5;
                dispatch_time_t popTime1 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 *NSEC_PER_SEC));
                
                dispatch_after(popTime1, dispatch_get_main_queue(), ^{
                    //发送数据到蓝牙外设
                    [self selectRequestDatatoBule:characteristic];
                    dispatch_time_t popTime2 = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds1 *NSEC_PER_SEC));
                    dispatch_after(popTime2, dispatch_get_main_queue(), ^{
                        //发送数据到蓝牙外设
                        [self selectRequestDatatoBule:characteristic];
                    });
                    
                });
                
            });
            //清空上一次测量数据
//            [self clearLastMeasureData];
        }
    }
}

- (void)selectRequestDatatoBule:(CBCharacteristic *)characteristicPM
{
    switch (_scalePer) {
        case lefuScale:
            [self lefuRequestDataToBlue:characteristicPM];
            break;
        case vScale:
            self.dataInteractCharacteristic = characteristicPM;
            break;
        case eBelterScale:
            [self ebelterRequestDataToBlue:characteristicPM];
            NSLog(@"PPPP%@", characteristicPM);
            break;
            
        default:
            break;
    }
}

//乐福称接受数据
- (void)lefuRequestDataToBlue:(CBCharacteristic *)achar
{
    Byte bytes[8];
    
    bytes[0] = 0xfe; // 1 FE 包头
    bytes[1] = 0x00; // 2 03 用户组号
    bytes[2] = 0x00; // 3 01 男  00 女
    bytes[3] = 0x00; // 4 02 运动员级别  0 普通  1 业余   2 专业
    bytes[4] = 0xA0; // 5 AA 身高
    bytes[5] = 0x12; // 6 19 年龄
    bytes[6] = 0x01; // 7 01 单位   01 千克  02 lb(英石)  03 ST:LB(英磅)
    bytes[7] = bytes[1]^bytes[2]^bytes[3]^bytes[4]^bytes[5]^bytes[6];  // 8 异或校检和
    NSData *dataa = [[NSData alloc] initWithBytes:bytes length:8];
    
    [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
}

//思麦德接收数据
- (void)vRequestDataToBlue:(CBCharacteristic *)achar
{
    Byte bytes[5];
    bytes[0] = 0x00; //
    bytes[1] = 0x01; // user
    bytes[2] = 0x01; // sex
    bytes[3] = 0x12; // age
    bytes[4] = 0xA0; // height
    NSData *dataa = [[NSData alloc] initWithBytes:bytes length:5];
    
    [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
}

//倍泰接收数据
- (void)ebelterRequestDataToBlue:(CBCharacteristic *)achar
{
    Byte bytes[7];
    bytes[0] = 0xFD;
    bytes[1] = 0x53;
    bytes[2] = 0x00;
    bytes[3] = 0x00;
    bytes[4] = _statusint<<6;
    bytes[5] = (0 << 7) | _ageInt;
    bytes[6] = _heightInt;
    NSData *dataa = [[NSData alloc] initWithBytes:bytes length:7];
    [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
}

//外设接收数据
//-(void)requestDataToBlue:(CBCharacteristic *)achar
//{
//    if (self.lefuScale) {
//        Byte bytes[8];
//    
//        bytes[0] = 0xfe; // 1 FE 包头
//        bytes[1] = 0x00; // 2 03 用户组号
//        bytes[2] = 0x00; // 3 01 男  00 女
//        bytes[3] = 0x00; // 4 02 运动员级别  0 普通  1 业余   2 专业
//        bytes[4] = 0xA0; // 5 AA 身高
//        bytes[5] = 0x12; // 6 19 年龄
//        bytes[6] = 0x01; // 7 01 单位   01 千克  02 lb(英石)  03 ST:LB(英磅)
//        bytes[7] = bytes[1]^bytes[2]^bytes[3]^bytes[4]^bytes[5]^bytes[6];  // 8 异或校检和
//        NSData *dataa = [[NSData alloc] initWithBytes:bytes length:8];
//        
//        [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
//    } else {
//        Byte bytes[5];
//        bytes[0] = 0x00; //
//        bytes[1] = 0x01; // user
//        bytes[2] = 0x01; // sex
//        bytes[3] = 0x12; // age
//        bytes[4] = 0xA0; // height
//        NSData *dataa = [[NSData alloc] initWithBytes:bytes length:5];
//        
//        [self.peripheral writeValue:dataa forCharacteristic:achar type:CBCharacteristicWriteWithResponse];
//    }
//    
//    
//}


//获取外设发来的数据，不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    [MBProgressHUD showSuccess:@"正在测量......."];
    //    NSString *msg = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    //    NSLog(@"--message:%@",msg);
    if (error)
    {
        NSLog(@"didUpadateValueForCharacteristicError: %@", error.localizedDescription);
        return;
    }
    
    [self.mgr stopScan];
//    NSString *uuidWRStr = self.isLefuScale ? @"0xFFF4" : @"1a2ea400-75b9-11e2-be05-0002a5d5c51b";
//    //外设发数据过来
//    // 底层测量一次会发两次数据过来，
//    if (self.isLefuScale) {
//        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidWRStr]])
//        {
//            SYLog(@"接收数据");
//            dispatch_once(&onceAnalyseData, ^{
//                [self analyseData:characteristic.value withPeripheral:peripheral];
//            });
//        }
//    } else {
//        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidWRStr]])
//        {
//            dispatch_once(&onceAnalyseData, ^{
//                [self analyseData:characteristic.value withPeripheral:peripheral];
//            });
//            
//        }
//    }
    NSLog(@" bbbbb%@", characteristic.value);
    NSString *uuidWRStr = nil;
    switch (_scalePer) {
        case lefuScale:
            uuidWRStr = @"0xFFF4";
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidWRStr]]) {
                dispatch_once(&onceAnalyseData, ^{
                    [self analyseData:characteristic.value withPeripheral:peripheral];
                });
            }
            break;
        case vScale:
            uuidWRStr =  @"1a2ea400-75b9-11e2-be05-0002a5d5c51b";
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidWRStr]]) {
//                dispatch_once(&onceAnalyseData, ^{
                    [self analyseData:characteristic.value withPeripheral:peripheral];
//                });
            }
            break;
        case eBelterScale:
            uuidWRStr = @"0xFFF4";
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:uuidWRStr]]) {
//                dispatch_once(&onceAnalyseData, ^{
                    [self analyseData:characteristic.value withPeripheral:peripheral];
//                });
            }
            break;
        default:
            break;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jiance) name:nil object:nil];
    
}

//app发送关机指令，使设备关机，反馈指令关闭app
- (void)changeUpdateStateAndCloseBLE:(CBCharacteristic *)aChar
{
    NSLog(@"发送关机指令");
    SYLog(@"Send device power off");
    
    Byte bytes[8];
    bytes[0] = 0xFD;
    bytes[1] = 0x35;
    bytes[2] = 0x00;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x00;
    bytes[6] = 0x00;
    bytes[7] = 0x35;
    
    [self.peripheral writeValue:[NSData dataWithBytes:bytes length:8] forCharacteristic:aChar type:CBCharacteristicWriteWithResponse];
    
}

//app发数据到蓝牙，是否接收到，没有则0.5s后重新发，最多发三次
- (void)jiance
{
    //    if (self.mgr.state == CBCentralManagerStatePoweredOff) {
    //        sleep(0.5);
    //        dispatch_once(&onceToken1, ^{
    //            self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //        });
    //
    //    }
    
    for (int i = 0; i < 3; i ++) {
        sleep(0.5);
        if (self.mgr.state == CBCentralManagerStatePoweredOff) {
            self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        }
    }
    
}

- (void)dealloc
{
    //    [super dealloc];
    onceAnalyseData = 0;
//    [SYNotificationCenter removeObserver:self];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

/**
 判断当前控制器是否显示
 */
- (BOOL)isVisible
{
    return (self.isViewLoaded && self.view.window);
}

// 接收到蓝牙数据 先分析
- (void)analyseData:(NSData *)data withPeripheral:(CBPeripheral *)aPer
{
    NSLog(@"开始接受数据");
    float tempFat = 0.0;
    float tempGuge = 0.0;
    float tempJiRou = 0.0;
    float tempNeiZang = 0.0;
    float tempShuiFen = 0.0;
    float tempReLiang = 0.0;
    float tempWeight = 0.0;
    float tempHeight = 0.0;
//    NSNumber *level = [NSNumber numberWithInt:0];
//    NSNumber *userTypt = [NSNumber numberWithInt:0];
//    NSNumber *sex = [NSNumber numberWithInt:0];
//    NSNumber *age = [NSNumber numberWithInt:0];
    NSNumber *height = [NSNumber numberWithInt:0];
    NSNumber *weight = [NSNumber numberWithInt:0];
//    NSString *device = @"";
    
    Byte *bytes = (Byte *)[data bytes];
    float weightf = 0.0;
    switch (_scalePer) {
        case lefuScale:
        {
            if (bytes[0] == 0xfd && bytes[1] == 0x33 && bytes[2] == 0 && bytes[3] == 0 && bytes[4] == 0 && bytes[5] == 0 && bytes[6] == 0 && bytes[7] == 0x33 && [self isVisible]){
                [MBProgressHUD showError:@"亲，测量出现错误，请在测一次"];
                return;
            }else{
                [MBProgressHUD hideHUD];
                unsigned int tempWeight0 = (unsigned char)bytes[4];
                unsigned int tempWeight1 = (unsigned char)bytes[5];
                tempWeight = (tempWeight0 << 8) | tempWeight1;
                weightf = tempWeight / 10.0;
                valueStr = [NSString stringWithFormat:@"%.1f kg", weightf];
                NSLog(@"体重是: %@-++++-%.1f",valueStr, weightf);
                
                [self createLabel:valueStr];
                [self.view setNeedsDisplay];
                [self getUserParmaterData:[NSString stringWithFormat:@"%.1f", weightf] selectionValue:1 gaoxueya:nil];
            }

        }
            break;
        case vScale:
        {
            [MBProgressHUD hideHUD];
            if (bytes[0] == 0x0 && bytes[1] == 0x0 && bytes[2] == 0x0 && bytes[3] == 0x0)
            {
                NSLog(@"体重值锁定");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self vRequestDataToBlue:self.dataInteractCharacteristic];
                });
                return;
            }
            
            if (bytes[0] != 0x0 && bytes[2] != 0x0 && bytes[3] != 0x0 && bytes[6] == 0xff && bytes[7] == 0xff && bytes[8] == 0xff && bytes[9] == 0xff)
            {
                unsigned int tempWeight0 = (unsigned char)bytes[4];
                unsigned int tempWeight1 = (unsigned char)bytes[5];
                tempWeight = (tempWeight0 << 8) | tempWeight1;
                weightf = tempWeight / 10.0;
                valueStr = [NSString stringWithFormat:@"%.1f kg", weightf];
                NSLog(@"体重是: %@--",valueStr);
                [self createLabel:valueStr];
                [self.view setNeedsDisplay];
                [self getUserParmaterData:[NSString stringWithFormat:@"%.1f", weightf] selectionValue:1 gaoxueya:nil];
                [MBProgressHUD showError:@"亲！脱了鞋袜能看更多指标哦"];
            }else {
                unsigned int tempWeight0 = (unsigned char)bytes[4];
                unsigned int tempWeight1 = (unsigned char)bytes[5];
                tempWeight = (tempWeight0 << 8) | tempWeight1;
                weightf = tempWeight / 10.0;
                valueStr = [NSString stringWithFormat:@"%.1f kg", weightf];
                NSLog(@"体重是: %@--",valueStr);
                [self createLabel:valueStr];
                [self.view setNeedsDisplay];
                [self getUserParmaterData:[NSString stringWithFormat:@"%.1f", weightf] selectionValue:1 gaoxueya:nil];
                // 体重为0时，秤只发送一个数据过来，正常情况是两次
                if (tempWeight == 0) {
                    [MBProgressHUD showError:@"未测您的身体信息,测量错误"];
                    return;
                }
            }
        }
            break;
        case eBelterScale:
        {

            if (bytes[0] == 0x00 || bytes[0] == 0xfb)
            {
                return;
            }
            
            if (bytes[0] == 0xff) {
                unsigned int tempWeight0 = (unsigned char)bytes[1];
                unsigned int tempWeight1 = (unsigned char)bytes[2];
                 tempWeight = ((tempWeight0 << 8) | tempWeight1) & 0x3FFF;
                weight = [NSNumber numberWithInt:tempWeight];
                SYLog(@"体重是: %ld",(long)tempWeight);
                // 体重为0时，秤只发送一个数据过来，正常情况是两次
                if (tempWeight == 0) {
                    self.isMeasureError = YES;
                    [MBProgressHUD showError:@"未测您的身体信息,测量错误"];
                    return;
                } else {
                    self.isMeasureError = NO;
                }
                
                
                if (bytes[11] == 0xff && (bytes[12] & 0xf0) == 0xf0) {
                    [MBProgressHUD showError:@"亲！脱了鞋袜能看更多指标哦"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                          self.isMeasureError = NO;
                    });
                  
                } else {
                    tempHeight = (unsigned char)bytes[10];
                    height = [NSNumber numberWithInt:tempHeight];
                    SYLog(@"身高是: %@",height);
                    NSLog(@"Byte = %s", bytes);
                    
                    NSLog(@"b12 = %hhu,, b13 ===%hhu", bytes[11], bytes[12]);
                    
                    unsigned char tempFat0 = (unsigned char)(bytes[12] & 0xf0);
                    tempFat0 = tempFat0 >> 4;
                    unsigned char tempFat1 = (unsigned char)bytes[11];
                    tempFat = (tempFat0 << 8) | tempFat1;
                    
                    

                    NSLog(@"tempF = %f", tempFat);
                    
                    tempGuge = (unsigned char)bytes[16];
                    
                    unsigned int tempJiRou0 = (unsigned char)bytes[14];
                    unsigned int tempJiRou1 = (unsigned char)bytes[15];
                    tempJiRou = (tempJiRou0 << 8) | tempJiRou1;
                    _jiRouScale = tempJiRou * 0.1;
                    tempJiRou = tempJiRou * tempWeight / 1000.0;
                    
                    tempNeiZang = (unsigned char)bytes[17];
                    
                    unsigned int tempShuiFen0 = (unsigned char)(bytes[12] & 0x0f);
                    unsigned int tempShuiFen1 = (unsigned char)bytes[13];
                    tempShuiFen = (tempShuiFen0 << 8) | tempShuiFen1;
                    
                    unsigned int tempReLiang0 = (unsigned char)bytes[18];
                    unsigned int tempReLiang1 = (unsigned char)bytes[19];
                    tempReLiang = (tempReLiang0 << 8) | tempReLiang1;
                }
            }
        
            
            NSNumber *fat = [NSNumber numberWithInt:tempFat];
            SYLog(@"脂肪是: %@",fat);
            
            NSNumber *guge = [NSNumber numberWithInt:tempGuge];
            SYLog(@"骨骼是: %@",guge);
           
            unsigned int tempHealthAge;
            if (data.length==17) {
                tempHealthAge = (unsigned char)bytes[16];
            }
            else{
                tempHealthAge = 0;
            }
//            NSNumber *HealthAge = [NSNumber numberWithInt:tempHealthAge];
            
            
            
            NSDate *now = [NSDate date];
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear;
            NSDateComponents *testDate = [calendar components:unitFlags fromDate:now];
            SYLog(@"testDate:%@", testDate);//%d-%d-%d-%d-%d-%d, 星期：%d
            valueStr = [NSString stringWithFormat:@"%.1f kg", tempWeight /10.0];
//            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            dispatch_once(&onceToken, ^{
            
            if (_bodyfatView.reLiang != tempReLiang) {
                
                
                
                _bodyfatView.fat = tempFat / 10.0;
            
                _bodyfatView.guGe = tempGuge / 10.0;
            
                _bodyfatView.jiRou = tempJiRou / 10.0;
                _bodyfatView.jiRouScale = _jiRouScale;
            
                _bodyfatView.neiZang = tempNeiZang;
            
                _bodyfatView.shuiFen = tempShuiFen / 10.0;
                _bodyfatView.reLiang = tempReLiang ;
                _bodyfatView.weight = tempWeight / 10.0;
                _bodyfatView.bmi = ((tempWeight * 1000) / (tempHeight * tempHeight));
                _bodyfatView.height = tempHeight;
                [_bodyfatView reloadText];
            
               [self.view addSubview:_bodyfatView];
                
                [_bodyfatView getUserWeightFatData];
                
                [self getUserParmaterData:[NSString stringWithFormat:@"%.1f", _bodyfatView.weight] selectionValue:1 gaoxueya:nil];
            }
            self.useAddviceWindow.hidden = YES;
             _bodyfatView.hidden = NO;
            

            
            [self createLabel:valueStr];
            NSLog(@"体重是%@", valueStr);
            [self.view setNeedsDisplay];
                

            
    }

            
            
            
            break;
            
        default:
            break;
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
